import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaozeyang
 * @date 2018/10/31 21:15
 * @description
 */
public class 三十九 {

    public static void main(String[] args) {
        System.out.println(combinationSum(new int[]{2, 3, 6, 7}, 7));
    }

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> item = new ArrayList<Integer>();
        for (int i = 0; i < candidates.length; i++) {
            for (int j = i; j < candidates.length; j++) {
                if (candidates[i] > candidates[j]) {
                    int s = candidates[j];
                    candidates[j] = candidates[i];
                    candidates[i] = s;
                }

            }
        }
        getSum(candidates, target, result, item, 0, 0);
        return result;
    }

    public static void getSum(int[] candidates, int target, List<List<Integer>> result, List<Integer> item, int sum, int idx) {
        if (sum == target) {
            result.add(new ArrayList<Integer>(item));
        } else {
            for (int i = idx; i < candidates.length; i++) {
                if (sum + candidates[i] > target) {
                    return;
                }
                item.add(candidates[i]);
                getSum(candidates, target, result, item, sum + candidates[i], i);
                item.remove(item.size() - 1);
            }
        }
    }
}
